package com.ehsunbehravesh.service.security.ejb.hash;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.Adler32;
import java.util.zip.CRC32;
import java.util.zip.Checksum;
import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.Stateless;

/**
 *
 * @author ehsun.behravesh
 */
@Stateless(name = "HashEJB")
@Local(HashLocalBusiness.class)
@Remote(HashRemoteBusiness.class)
public class HashBean implements HashLocalBusiness, HashRemoteBusiness {

  @Override
  public byte[] hashMD5(byte[] data) throws HashServiceException {
    try {
      MessageDigest md = MessageDigest.getInstance("MD5");
      byte[] result = md.digest(data);
      return result;
    } catch (NoSuchAlgorithmException ex) {
      Logger.getLogger(HashBean.class.getName()).log(Level.SEVERE, null, ex);
      throw new HashServiceException(ex);
    }
  }

  @Override
  public byte[] hashSHA1(byte[] data) throws HashServiceException {
    try {
      MessageDigest md = MessageDigest.getInstance("SHA-1");
      byte[] result = md.digest(data);
      return result;
    } catch (NoSuchAlgorithmException ex) {
      Logger.getLogger(HashBean.class.getName()).log(Level.SEVERE, null, ex);
      throw new HashServiceException(ex);
    }
  }

  @Override
  public byte[] hashSHA256(byte[] data) throws HashServiceException {
    try {
      MessageDigest md = MessageDigest.getInstance("SHA-256");
      byte[] result = md.digest(data);
      return result;
    } catch (NoSuchAlgorithmException ex) {
      Logger.getLogger(HashBean.class.getName()).log(Level.SEVERE, null, ex);
      throw new HashServiceException(ex);
    }
  }

  @Override
  public byte[] hashSHA512(byte[] data) throws HashServiceException {
    try {
      MessageDigest md = MessageDigest.getInstance("SHA-512");
      byte[] result = md.digest(data);
      return result;
    } catch (NoSuchAlgorithmException ex) {
      Logger.getLogger(HashBean.class.getName()).log(Level.SEVERE, null, ex);
      throw new HashServiceException(ex);
    }
  }

  @Override
  public byte[] hashSHA3(byte[] data) {
    throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
  }

  @Override
  public long sumCRC32(byte[] data) throws HashServiceException {
    Checksum crc32 = new CRC32();
    crc32.update(data, 0, data.length);
    long value = crc32.getValue();
    return value;
  }

  @Override
  public long sumAdler32(byte[] data) throws HashServiceException {
    Checksum adler32 = new Adler32();
    adler32.update(data, 0, data.length);
    long value = adler32.getValue();
    return value;
  }
}
